<template>
  <div class="container">
    <el-row style="height: 100%">
      <el-col style="height: 100%; padding: 20px" :span="11">
        <div class="left">
          <h3 style="margin-bottom: 10px">危险源</h3>
          <list-table-new
            @focusInput="focusInput"
            @changeInput="changeInput"
            v-bind="riskSourceConfig"
            ref="riskSourceTable"
          ></list-table-new>
        </div>
      </el-col>
      <el-col
        style="height: 100%; border-left: 10px #f2f3f8 solid; padding: 20px"
        :span="13"
      >
        <div class="right">
          <h3>风险列表</h3>
          <riskItem
            :riskSourceId="selectId"
            :pageType="pageType"
            ref="riskItem"
          ></riskItem>
        </div>
      </el-col>
    </el-row>
    <input
      type="file"
      ref="uploadFile"
      style="display: none"
      accept=".xls,.xlsx"
      :multiple="false"
      @change="autoUploadFile"
    />
    <dialogPublic
      :title="title"
      :show.sync="show"
      v-if="show"
      height="400"
      @doSubmit="doSubmit"
      @doClose="() => (show = false)"
    >
      <editForm
        :formConfig="formConfig"
        ref="editForm"
        :formData="editFormData"
      ></editForm>
    </dialogPublic>
  </div>
</template>

<script>
import {
  queryRiskSourceList,
  queryRiskSourceType,
  addRiskSource,
  updateRiskSource,
  deleteRiskSource,
  importRisk,
} from "@/api/standardManagement/operateRiskLibrary.js";
import riskItem from "./riskItem.vue";
export default {
  props: {
    pageType: {
      type: String,
      default: "list",
    },
  },
  components: { riskItem },
  data() {
    return {
      title: "",
      selectId: "",
      syncTime: "",
      show: false,
      searchData: {},
      //危险源列表
      riskSourceConfig: {
        showIndex: true,
        selectionShow: false,
        showFilterBtn: false,
        showCustomBtn: false,
        highlightCurrentRow: true,
        searchObj: {
          searchMethod: (params, formData) => {
            this.getRiskSourceData(params, formData);
          },
          searchArr: [
            {
              type: "select",
              label: "一级分类",
              model: "firstTypeName",
              placeholder: "请选择",
            },
            {
              type: "select",
              label: "二级分类",
              model: "secondTypeName",
              placeholder: "请选择",
            },
            {
              type: "text",
              label: "三级分类",
              model: "thirdTypeName",
              placeholder: "输入",
            },
            {
              type: "text",
              label: "四级分类",
              model: "fourthTypeName",
              placeholder: "请输入",
            },
          ],
          queryData: {
            page: 1,
            pageSize: 15,
          },
        },
        tableMethods: {
          rowClick: (row) => {
            this.selectId = row.id;
          },
        },
        actionList: [
          {
            name: "新增",
            icon: "el-icon-plus",
            disabled: !this.$store.getters.isBtnAuth("add"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: () => {
              this.addRiskSource();
            },
          },
          {
            name: "导入",
            icon: "el-icon-upload",
            disabled: !this.$store.getters.isBtnAuth("import"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: () => {
              this.uploadFile();
            },
          },
          {
            name: "导出",
            icon: "icon-daochu",
            disabled: !this.$store.getters.isBtnAuth("export"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.export();
            },
          },
          {
            name: "下载模板",
            icon: "el-icon-download",
            disabled: !this.$store.getters.isBtnAuth("download"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: () => {
              this.download();
            },
          },
        ],
        column: [
          {
            label: "一级分类",
            prop: "firstTypeName",
            sortable: "custom",
          },
          {
            label: "二级分类",
            prop: "secondTypeName",
            sortable: "custom",
          },
          {
            label: "三级分类",
            prop: "thirdTypeName",
            sortable: "custom",
          },
          {
            label: "四级分类",
            prop: "fourthTypeName",
            sortable: "custom",
          },
          {
            label: "操作",
            textAlign: "center",
            type: "button",
            scopeType: "textButton",
            hide: false,
            //width:"240px",
            buttonArr: [
              {
                text: "编辑",
                icon: "el-icon-edit",
                isShow: (row) => {
                  return true;
                },
                disabled: !this.$store.getters.isBtnAuth("edit"), //控制按钮的禁用
                content: "未授权功能", //禁用提示内容
                methods: (row) => {
                  this.editFormData = row;
                  this.getSecondRiskType(row.firstTypeId, "formItem");
                  this.title = "编辑危险源";
                  this.show = true;
                },
              },
              {
                text: "删除",
                icon: "el-icon-delete-solid",
                isShow: (row) => {
                  return true;
                },
                disabled: !this.$store.getters.isBtnAuth("delete"), //控制按钮的禁用
                content: "未授权功能", //禁用提示内容
                methods: (row) => {
                  this.$confirm("确定要删除这条数据吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                    .then(() => {
                      this.delete(row.id);
                    })
                    .catch(() => {});
                },
              },
            ],
          },
        ],
        tableData: [],
        paginationObj: {
          pageSizes: [15, 30, 50, 100],
        },
        totalNumber: 0,
      },
      formConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "一级分类",
            prop: "firstTypeName",
            type: "select",
            span: 12,
            placeholder: "请选择或直接输入",
            required: true,
            filterable: true,
            allowCreate: true,
            selectOption: [],
            methods: (arr, item) => {
              this.getSecondRiskType(item.firstTypeName, "formItem");
              // if (arr.label) {
              //   this.firstTypeName = arr.label;
              // } else {
              //   this.parentTypeName = item.firstTypeName;
              // }
            },
          },
          {
            label: "二级分类",
            prop: "secondTypeName",
            type: "select",
            span: 12,
            placeholder: "请选择或直接输入",
            required: false,
            filterable: true,
            allowCreate: true,
            selectOption: [],
            // methods: (arr, item) => {
            //   if (arr.label) {
            //     this.secondTypeName = arr.label;
            //   } else {
            //     this.secondTypeName = item.secondTypeName;
            //   }
            // },
          },
          {
            label: "三级分类",
            prop: "thirdTypeName",
            type: "text",
            span: 12,
            required: false,
          },
          {
            label: "四级分类",
            prop: "fourthTypeName",
            type: "text",
            span: 12,
            required: false,
          },
        ],
      },
      //弹出框表单数据
      editFormData: {},
    };
  },
  created() {
    if (this.pageType != "list") {
      this.riskSourceConfig.actionList = [
        {
          name: "前往添加",
          icon: "el-icon-plus",
          method: (row) => {
            this.goDetailPage();
          },
        }
      ];
      this.riskSourceConfig.column[4].hide = true;
    } else {
      this.getFirstRiskType();
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    //初始化数据
    init() {
      this.$refs.riskSourceTable.searchData();
    },
    //获取危险源列表
    getRiskSourceData(params, sortStr) {
      let queryData = Object.assign({}, params);
      this.searchData = params;
      if (sortStr.length > 0) {
        queryData.orders = sortStr;
      }
      queryRiskSourceList(queryData).then((res) => {
        this.$set(this.riskSourceConfig, "tableData", res.data.records);
        this.$set(this.riskSourceConfig, "totalNumber", res.data.total);
        this.selectId = res.data.records[0].id;
        this.$refs.riskSourceTable.setCurrentRow(res.data.records[0]);
      });
    },

    //搜索栏下拉框获取焦点
    focusInput(model, searchForm) {
      if (model === "secondTypeName") {
        if (!searchForm.firstTypeName || searchForm.firstTypeName == "") {
          this.$message.warning("请先选择一级分类");
        }
      }
    },
    //输入框改变
    changeInput(model, searchForm) {
      if (model === "firstTypeName") {
        let arr = this.getSecondRiskType(searchForm.firstTypeName, "search");
      }
    },
    //查询一级分类下拉框
    getFirstRiskType() {
      queryRiskSourceType({ firstName: 0 }).then((res) => {
        if (res.code == 200) {
          let arr = res.data.map((item) => {
            let obj = {
              label: item.firstTypeName,
              value: item.firstTypeName,
            };
            return obj;
          });
          this.$set(
            this.riskSourceConfig.searchObj.searchArr[0],
            "option",
            arr
          );
          this.$set(this.formConfig.itemArr[0], "selectOption", arr);
        }
      });
    },
    //查询二级分类下拉框
    getSecondRiskType(name, type) {
      queryRiskSourceType({ firstName: name }).then((res) => {
        if (res.code == 200) {
          let arr = res.data.map((item) => {
            let obj = {
              label: item.secondTypeName,
              value: item.secondTypeName,
            };
            return obj;
          });
          if (type == "search") {
            this.$set(
              this.riskSourceConfig.searchObj.searchArr[1],
              "option",
              arr
            );
          } else {
            this.$set(this.formConfig.itemArr[1], "selectOption", arr);
          }
        }
      });
    },
    //新增危险源
    addRiskSource() {
      this.editFormData = {};
      this.title = "新增危险源";
      this.show = true;
    },
    //表单提交
    async doSubmit() {
      const params = await this.$refs.editForm.getFormData();
      if (this.title == "新增危险源") {
        addRiskSource(params).then(
          (res) => {
            if (res.code == 200) {
              this.$message.success(res.description);
              this.show = false;
              this.$refs.riskSourceTable.searchData();
            }
          },
          (error) => {
            this.$message.error(error);
          }
        );
      } else {
        updateRiskSource(params).then(
          (res) => {
            if (res.code == 200) {
              this.$message.success(res.description);
              this.show = false;
              this.$refs.riskSourceTable.searchData();
            }
          },
          (error) => {
            this.$message.error(error);
          }
        );
      }
    },
    //删除配置项详情
    delete(id) {
      deleteRiskSource({ id: id }).then(
        (res) => {
          if (res.code == 200) {
            this.$message.success(res.description);
            this.$refs.riskSourceTable.searchData();
          }
        },
        (error) => {
          this.$message.error(error);
        }
      );
    },
    //导出
    export() {
      let paramStr = "";
      let params = this.searchData;
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
          if (params[key] && params[key] != "") {
            paramStr += `${key}=${params[key]}&`;
          }
        }
      }
      paramStr = paramStr.substring(0, paramStr.length - 1);
      let path = `eam-service-standard/riskSources/export?${paramStr}`;
      let fileName = `作业风险库`;
      this.$utils.downloadFile(null, fileName, path);
    },
    //下载模板
    download() {
      let path = "eam-service-standard/riskSources/template";
      this.$utils.downloadFile(null, "作业风险库导入模板", path);
    },
    //点击选择文件
    uploadFile() {
      const fileObj = this.$refs.uploadFile;
      fileObj.click();
    },
    //上传选择的文件
    async autoUploadFile(e, file) {
      let riskFile = this.$refs.uploadFile.files[0];
      if (riskFile.length == 0) {
        return;
      } else {
        let params = {
          id: this.$store.state.user.userInfo.appId,
        };
        const formData = new FormData();
        formData.append("file", riskFile);
        await importRisk(params, formData);
        this.$refs.uploadFile.value = null;
        this.$message.success("导入成功");
        this.updateData();
      }
    },
    goDetailPage() {
      const { href } = this.$router.resolve({
        name: "operateRiskLibrary",
      });
      window.open(href, "_blank");
    },
    //获取选中的数据
    getSelectData() {
      return this.$refs.riskItem.getSelectData();
    },
  },
};
</script>



<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  .left {
    width: 100%;
    height: calc(100% - 40px);
    text-align: left;
    position: relative;
    .syncTime {
      position: absolute;
      left: 10px;
      bottom: -35px;
    }
  }
  .right {
    width: 100%;
    height: calc(100% - 40px);
    text-align: left;
  }
}
</style>

